# -*- coding: utf-8 -*-

import base64
from django.contrib import auth
from django.contrib.auth import login, logout
from django.shortcuts import redirect
from django.utils.translation import gettext_lazy as _
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework.views import APIView
from core.response import JsonResponse
from apps.sys.login.serializers import *
from rest_framework.permissions import AllowAny
from captcha.views import CaptchaStore, captcha_image
from rest_framework.throttling import AnonRateThrottle


class CaptchaView(APIView):
    """
    获取验证码接口
    """

    authentication_classes = []
    permission_classes = []
    throttle_classes = [AnonRateThrottle]  # 添加限流防止暴力请求

    def get(self, request):
        hashkey = CaptchaStore.generate_key()
        id = CaptchaStore.objects.filter(hashkey=hashkey).first().id
        image = captcha_image(request, hashkey)
        # 将图片转换为base64
        image_base = base64.b64encode(image.content)
        data = {
            "id": id,
            "img": image_base.decode("utf-8"),
            "captchaEnabled": True,
        }
        return JsonResponse(data=data)


class LoginView(TokenObtainPairView):
    """
    登录接口
    """

    serializer_class = LoginSerializer
    permission_classes = []


class LogoutView(APIView):
    """退出接口"""

    permission_classes = [AllowAny]

    def post(self, request):
        logout(request)
        return JsonResponse(msg="注销成功")


class ApiLogin(APIView):
    """接口文档的登录接口"""

    serializer_class = ApiLoginSerializer
    authentication_classes = []
    permission_classes = []

    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")
        user_obj = auth.authenticate(request, username=username, password=password)
        if user_obj:
            login(request, user_obj)
            return redirect("/")
        else:
            return JsonResponse(msg="账号/密码错误")
